﻿using Api.Shared.Model.Web.Login;
using Api.Shared.Responsitory.Sqlite;
using Api.Shared.Sugar;
using Api.Shared.Utils;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FitterTest.Controllers
{
    [Route("api/private/v1/[controller]/[action]")]
    [ApiController]
    [EnableCors("any")]
    public class MenusController : ControllerBase
    {
        private readonly ISugarClientService helper;
        private readonly MySession mySession;
        private readonly SqliteRespository<RolesItemNew> roleRes;
        private readonly ILogger<MenusController> logger;

        public MenusController([FromKeyedServices(nameof(SqlName.sqlite))] ISugarClientService helper, MySession mySession, SqliteRespository<RolesItemNew> roleRes, ILogger<MenusController> logger)
        {
            this.helper = helper;
            this.mySession = mySession;
            this.roleRes = roleRes;
            this.logger = logger;
        }



        [HttpGet]
        public IActionResult Menus()
        {
            string userRole = mySession.user?.RoleName ?? "";

            if (mySession.UsersRole.TryGetValue(userRole, out int rolesItemNewId))
            {
                //根据用户等级找到角色
                mySession.RolesItemNew = roleRes.FindRolesItemNewById(
                    rolesItemNewId
                );

                //一级目录   mySession.RolesItemNew.children
                List<MenuItemNew>? menuItemlist = roleRes.QueryLevelOne();

                mySession.RolesItemNew.children = menuItemlist
                    ?.Where(
                        x =>
                            x.parentMenuItemId
                                .Split(',')
                                .Contains(mySession.RolesItemNew.id.ToString())
                    )
                    .ToList();

                //SetMenuItemNewChildren(mySession.RolesItemNew.children);

                // 在 foreach 前增加空值判断，防止 CS8602 空引用解引用异常
                if (mySession.RolesItemNew.children != null)
                {
                    foreach (var menuItem in mySession.RolesItemNew.children)
                    {
                        //menuItem.children
                        var m2 = roleRes.QueryLevelTwo();
                        menuItem.children = m2.Where(
                                x =>
                                    x.parentMenuItemId.Split(',').Contains(menuItem.id.ToString())
                                    && x.parentMenuItemId
                                        .Split(',')
                                        .Contains(mySession.RolesItemNew.id.ToString())
                            )
                            .ToList();
                    }

                    foreach (var menuItem in mySession.RolesItemNew.children)
                    {
                        if (menuItem.children != null)
                        {
                            foreach (var menuItem2 in menuItem.children)
                            {
                                //menuItem2.children
                                var m3 = roleRes.QueryLevelThree();

                                menuItem2.children = m3.Where(
                                        x =>
                                            x.parentMenuItemId.Split(',').Contains(menuItem2.id.ToString())
                                            && x.parentMenuItemId
                                                .Split(',')
                                                .Contains(menuItem.id.ToString())
                                            && x.parentMenuItemId
                                                .Split(',')
                                                .Contains(mySession.RolesItemNew.id.ToString())
                                    )
                                    .ToList();
                            }
                        }
                    }
                }
                foreach (var menuItem in mySession.RolesItemNew.children)
                {
                    //menuItem.children
                    var m2 = roleRes.QueryLevelTwo();
                    menuItem.children = m2.Where(
                            x =>
                                x.parentMenuItemId.Split(',').Contains(menuItem.id.ToString())
                                && x.parentMenuItemId
                                    .Split(',')
                                    .Contains(mySession.RolesItemNew.id.ToString())
                        )
                        .ToList();
                }

                foreach (var menuItem in mySession.RolesItemNew.children)
                {
                    foreach (var menuItem2 in menuItem.children)
                    {
                        //menuItem2.children
                        var m3 = roleRes.QueryLevelThree();

                        menuItem2.children = m3.Where(
                                x =>
                                    x.parentMenuItemId.Split(',').Contains(menuItem2.id.ToString())
                                    && x.parentMenuItemId
                                        .Split(',')
                                        .Contains(menuItem.id.ToString())
                                    && x.parentMenuItemId
                                        .Split(',')
                                        .Contains(mySession.RolesItemNew.id.ToString())
                            )
                            .ToList();
                    }
                }
            }

            return Ok(mySession.MenuItemsNew);
        }



        [HttpGet]
        public IActionResult GetProMenus([FromQuery] QueryInfo queryInfo)
        {
            if (queryInfo.Pagenum <= 0)
            {
                return StatusCode(204, "Failed");
            }
            if (queryInfo.Pagesize <= 0)
            {
                return StatusCode(204, "Failed");
            }
            int totalNumber = 0;
            var exp = Expressionable.Create<MenuItemNew>();
            exp.AndIF(!string.IsNullOrWhiteSpace(queryInfo.Query), x => x.authName.Contains(queryInfo.Query));

            var menus = this.helper.Db.Queryable<MenuItemNew>()
            .Where(exp.ToExpression())
            .Where(x => x.path.Contains("board") || x.path.Contains("circle"))
            .ToPageList(queryInfo.Pagenum, queryInfo.Pagesize, ref totalNumber);

            var resultData = new
            {
                total = totalNumber,
                pagenum = queryInfo.Pagenum,
                menus = menus
            };
            if (menus.Count > 0)
            {
                return Ok(resultData);
            }
            else
            {
                return StatusCode(204, "Failed");
            }
        }


        [HttpGet("{tableId}")]
        public async Task<IActionResult> GetMenuById(string tableId)
        {
            var menu = await this.helper.Db.Queryable<MenuItemNew>().InSingleAsync(int.Parse(tableId));
            if (menu != null)
            {
                return Ok(menu);
            }
            else
            {
                return StatusCode(204, "Failed");
            }
        }


        [HttpPut("{tableId}")]
        public async Task<IActionResult> UpdateMenuByIdAndModel(string tableId, [FromBody] MenuItemNew menu)
        {
            //var zhizuo = await helper.Db.Queryable<ZhizuoImpl>().ToListAsync();
            var b = helper.Db.Queryable<MenuItemNew>().Any(x => x.authName == menu.authName);
            if (b)
            {
                return StatusCode(204, "名字重复");
            }
            if (int.Parse(tableId) == menu.tableId)
            {

                int count = await this.helper.Db.Updateable<MenuItemNew>(menu).ExecuteCommandAsync();
                if (count > 0)
                {
                    return Ok();
                }
                return StatusCode(204, "Failed");
            }
            else
            {
                return StatusCode(204, "Failed");
            }

        }
    }
}
